﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Web;
using TimberSmart.Business.Contracts;

namespace TimberSmart.Web
{
    public class AuthToken : IAuthToken
    {
        public string Username { get; set; }
        public byte[] PasswordHash { get; set; }

        public static AuthToken CreateToken(AuthenticationHeaderValue authorization)
        {
            AuthToken token = new AuthToken();
            string[] authSplit;
            switch (authorization.Scheme.Trim().ToLower())
            {
                case "none":
                    authSplit = authorization.Parameter.Split(":".ToCharArray(), 2);
                    if (authSplit.Length != 2) return null;

                    return new AuthToken()
                        {
                            Username = authSplit[0],
                            PasswordHash = Encoding.Unicode.GetBytes(authSplit[1])                        
                        };
                case "basic":
                    authSplit = authorization.Parameter.Split(":".ToCharArray(), 2);
                    if (authSplit.Length != 2) return null;

                    return new AuthToken()
                        {
                            Username = authSplit[0],
                            PasswordHash = Encoding.Unicode.GetBytes(authSplit[1])                        
                        };
                default:
                    return null;
            }
        }
    }
}